<template>
  <div class="pagination-container">
    <!-- 分页信息 -->
    <div class="pagination-info">
      <span class="text-sm text-gray-700">
        显示第 
        <span class="font-medium">{{ startItem }}</span>
        -
        <span class="font-medium">{{ endItem }}</span>
        条，共 
        <span class="font-medium">{{ total }}</span>
        条结果
      </span>
    </div>
    
    <!-- 分页控件 -->
    <nav
      class="pagination-nav"
      aria-label="分页导航"
    >
      <div class="pagination-buttons">
        <!-- 上一页 -->
        <button
          :disabled="currentPage <= 1"
          class="pagination-btn pagination-btn--prev"
          @click="goToPage(currentPage - 1)"
        >
          <ChevronLeftIcon class="w-4 h-4" />
          <span class="hidden sm:inline ml-1">上一页</span>
        </button>
        
        <!-- 页码按钮 -->
        <div class="pagination-pages">
          <!-- 第一页 -->
          <button
            v-if="showFirstPage"
            :class="[
              'pagination-page',
              { 'pagination-page--active': currentPage === 1 }
            ]"
            @click="goToPage(1)"
          >
            1
          </button>
          
          <!-- 省略号 -->
          <span
            v-if="showStartEllipsis"
            class="pagination-ellipsis"
          >
            ...
          </span>
          
          <!-- 中间页码 -->
          <button
            v-for="page in visiblePages"
            :key="page"
            :class="[
              'pagination-page',
              { 'pagination-page--active': currentPage === page }
            ]"
            @click="goToPage(page)"
          >
            {{ page }}
          </button>
          
          <!-- 省略号 -->
          <span
            v-if="showEndEllipsis"
            class="pagination-ellipsis"
          >
            ...
          </span>
          
          <!-- 最后一页 -->
          <button
            v-if="showLastPage"
            :class="[
              'pagination-page',
              { 'pagination-page--active': currentPage === totalPages }
            ]"
            @click="goToPage(totalPages)"
          >
            {{ totalPages }}
          </button>
        </div>
        
        <!-- 下一页 -->
        <button
          :disabled="currentPage >= totalPages"
          class="pagination-btn pagination-btn--next"
          @click="goToPage(currentPage + 1)"
        >
          <span class="hidden sm:inline mr-1">下一页</span>
          <ChevronRightIcon class="w-4 h-4" />
        </button>
      </div>
    </nav>
    
    <!-- 每页条数选择器 -->
    <div
      v-if="showPageSizeSelector"
      class="page-size-selector"
    >
      <label class="text-sm text-gray-700 mr-2">每页显示</label>
      <select
        :value="pageSize"
        class="page-size-select"
        @change="handlePageSizeChange"
      >
        <option
          v-for="size in pageSizeOptions"
          :key="size"
          :value="size"
        >
          {{ size }}
        </option>
      </select>
      <span class="text-sm text-gray-700 ml-1">条</span>
    </div>
  </div>
</template>

<script setup>
import { computed } from 'vue'
import { ChevronLeftIcon, ChevronRightIcon } from '@heroicons/vue/24/outline'
import { logger } from '@/utils/logger'

const props = defineProps({
  currentPage: {
    type: Number,
    required: true,
    validator: (value) => value >= 1
  },
  totalPages: {
    type: Number,
    required: true,
    validator: (value) => value >= 0
  },
  total: {
    type: Number,
    required: true,
    validator: (value) => value >= 0
  },
  pageSize: {
    type: Number,
    default: 20
  },
  pageSizeOptions: {
    type: Array,
    default: () => [10, 20, 50, 100]
  },
  showPageSizeSelector: {
    type: Boolean,
    default: true
  },
  maxVisiblePages: {
    type: Number,
    default: 5,
    validator: (value) => value >= 3 && value % 2 === 1
  }
})

const emit = defineEmits(['page-change', 'page-size-change'])

// 计算属性
const startItem = computed(() => {
  if (props.total === 0) return 0
  return (props.currentPage - 1) * props.pageSize + 1
})

const endItem = computed(() => {
  const end = props.currentPage * props.pageSize
  return Math.min(end, props.total)
})

const visiblePages = computed(() => {
  const pages = []
  const half = Math.floor(props.maxVisiblePages / 2)
  
  let start = Math.max(1, props.currentPage - half)
  let end = Math.min(props.totalPages, props.currentPage + half)
  
  // 调整范围以保持固定数量的页码
  if (end - start + 1 < props.maxVisiblePages) {
    if (start === 1) {
      end = Math.min(props.totalPages, start + props.maxVisiblePages - 1)
    } else if (end === props.totalPages) {
      start = Math.max(1, end - props.maxVisiblePages + 1)
    }
  }
  
  // 避免显示第一页和最后一页（它们单独处理）
  const actualStart = start === 1 ? 2 : start
  const actualEnd = end === props.totalPages ? props.totalPages - 1 : end
  
  for (let i = actualStart; i <= actualEnd; i++) {
    if (i >= 1 && i <= props.totalPages) {
      pages.push(i)
    }
  }
  
  return pages
})

const showFirstPage = computed(() => {
  return props.totalPages > 1 && !visiblePages.value.includes(1)
})

const showLastPage = computed(() => {
  return props.totalPages > 1 && !visiblePages.value.includes(props.totalPages)
})

const showStartEllipsis = computed(() => {
  return showFirstPage.value && visiblePages.value.length > 0 && visiblePages.value[0] > 2
})

const showEndEllipsis = computed(() => {
  return showLastPage.value && visiblePages.value.length > 0 && 
         visiblePages.value[visiblePages.value.length - 1] < props.totalPages - 1
})

// 事件处理
const goToPage = (page) => {
  if (page < 1 || page > props.totalPages || page === props.currentPage) {
    return
  }
  
  logger.userAction('分页跳转', { fromPage: props.currentPage, toPage: page })
  emit('page-change', page)
}

const handlePageSizeChange = (event) => {
  const newPageSize = parseInt(event.target.value)
  
  logger.userAction('修改每页条数', { 
    fromPageSize: props.pageSize, 
    toPageSize: newPageSize 
  })
  
  emit('page-size-change', newPageSize)
}
</script>

<style scoped>
.pagination-container {
  @apply flex flex-col sm:flex-row sm:items-center sm:justify-between;
  @apply space-y-3 sm:space-y-0 py-4;
}

.pagination-info {
  @apply flex-shrink-0;
}

.pagination-nav {
  @apply flex-1 flex justify-center;
}

.pagination-buttons {
  @apply flex items-center space-x-1;
}

.pagination-btn {
  @apply inline-flex items-center px-3 py-2 text-sm font-medium;
  @apply text-gray-500 bg-white border border-gray-300 rounded-md;
  @apply hover:bg-gray-50 hover:text-gray-700;
  @apply disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:bg-white disabled:hover:text-gray-500;
  @apply transition-colors duration-200;
}

.pagination-pages {
  @apply flex items-center space-x-1 mx-2;
}

.pagination-page {
  @apply inline-flex items-center justify-center w-10 h-10 text-sm font-medium;
  @apply text-gray-500 bg-white border border-gray-300 rounded-md;
  @apply hover:bg-gray-50 hover:text-gray-700;
  @apply transition-colors duration-200;
}

.pagination-page--active {
  @apply bg-blue-600 text-white border-blue-600;
  @apply hover:bg-blue-700 hover:text-white;
}

.pagination-ellipsis {
  @apply inline-flex items-center justify-center w-10 h-10 text-sm;
  @apply text-gray-400;
}

.page-size-selector {
  @apply flex items-center flex-shrink-0;
}

.page-size-select {
  @apply px-3 py-1 text-sm border border-gray-300 rounded-md;
  @apply focus:ring-2 focus:ring-blue-500 focus:border-blue-500;
  @apply bg-white;
}

/* 响应式设计 */
@media (max-width: 640px) {
  .pagination-container {
    @apply space-y-2;
  }
  
  .pagination-buttons {
    @apply space-x-0.5;
  }
  
  .pagination-btn {
    @apply px-2 py-1.5;
  }
  
  .pagination-page {
    @apply w-8 h-8 text-xs;
  }
  
  .pagination-ellipsis {
    @apply w-8 h-8;
  }
  
  .page-size-selector {
    @apply justify-center;
  }
}
</style>
